package com.atguigu.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.mall.auth.feign.MemberFeignService;
import com.atguigu.mall.auth.vo.SocialUser;
import lombok.AllArgsConstructor;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.swing.text.html.parser.Entity;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zststart
 * @create 2022-06-11 18:03
 */
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    //处理社交登陆请求
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("client_id","2077705774");
        map.put("client_secret","40af02bd1c7e435ba6a6e9cd3bf799fd");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.mall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("api.weibo.com", "/oauth2/access_token", "post", null, null, map);
        if(response.getStatusLine().getStatusCode()==200){
            //获取到了
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户
            //如果当前用户是第一次进网站，自动注册进来
            //登陆或者注册这个用户
            R r = memberFeignService.login(socialUser);
            if(r.getCode()==0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                //TODO：子域session共享问题；使用JSON的序列化对象数据到redis中
                session.setAttribute("loginUser",data);
                return  "redirect:http://mall.com";
            }else {
                return "redirect:http://auth.mall.com/login.html";
            }

        }else {
            return "redirect:http://auth.mall.com/login.html";
        }
    }
}
